﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Calendar;
using BussinesLayer.MainView;
using BussinesLayer.Appointments;
using System.Runtime.InteropServices;
using ViewLayer.Appointments;
using ModelLayer.Appointments;
using BussinesLayer.Patients;
using ViewLayer.Patients;
using ModelLayer;

namespace ViewLayer.Calendar
{
    public partial class UserControlCalendar : UserControl
    {
        bool leftClick = true;
        bool tooltipShown = false;
        AppointmentRegistrationController update = new AppointmentRegistrationController();
        MedAgendaEntities entities = new MedAgendaEntities();
        //private IntPtr m_processHandle = IntPtr.Zero;

        public UserControlCalendar()
        {
            InitializeComponent();
            dayViewCalendar.Parent = this;
            dayViewCalendar.AllowInplaceEditing = true;
            dayViewCalendar.StartDate = DateTime.Now;
            dayViewCalendar.OnNewAppointment += new EventHandler<NewAppointmentEventArgs>(dayViewCalendar_OnNewAppointment);
            dayViewCalendar.OnSelectionChanged += new EventHandler<EventArgs>(dayViewCalendar_OnSelectionChanged);
            dayViewCalendar.OnResolveAppointments += new EventHandler<ResolveAppointmentsEventArgs>(dayViewCalendar_OnResolveAppointments);
            dayViewCalendar.MouseMove += new MouseEventHandler(dayViewCalendar_MouseMove);
            dayViewCalendar.OnAppointmentMove += new EventHandler<AppointmentEventArgs>(dayViewCalendar_OnAppointmentMove);
            dayViewCalendar.Renderer = new Office12Renderer();
            //m_processHandle = GetCurrentProcess();
        }

        #region eventos
        void dayViewCalendar_MouseMove(object sender, MouseEventArgs e)
        {
            if (dayViewCalendar.GetAppointmentAt(e.X, e.Y) == null || dayViewCalendar.GetAppointmentAt(e.X, e.Y).Subject == "Creando nueva cita...")
                toolTipUserControlCalendar.Active = false;
            else
                toolTipUserControlCalendar.Active = true;
        }

        void dayViewCalendar_OnAppointmentMove(object sender, AppointmentEventArgs e)
        {
            ((Label)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxVisitProperties"])).Controls["labelApointmentDate"])).Text = dayViewCalendar.SelectedAppointment.StartDate.ToShortDateString();//dayViewCalendar.SelectionStart.ToString();
            ((Label)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxVisitProperties"])).Controls["horaEntradaLabel"])).Text = dayViewCalendar.SelectedAppointment.StartDate.ToShortTimeString();//dayViewCalendar.SelectionStart.ToString();
            ((Label)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxVisitProperties"])).Controls["horaSalidaLabel"])).Text = dayViewCalendar.SelectedAppointment.EndDate.ToShortTimeString();//dayViewCalendar.SelectionEnd.ToString();
        }

        void dayViewCalendar_OnResolveAppointments(object sender, ResolveAppointmentsEventArgs e)
        {
            List<Appointment> m_Apps = new List<Appointment>();
            foreach (Appointment m_App in AppointmentManager.Appointments)
                if ((m_App.StartDate >= e.StartDate) && (m_App.StartDate <= e.EndDate))
                    m_Apps.Add(m_App);
            e.Appointments = m_Apps;
        }

        void dayViewCalendar_OnSelectionChanged(object sender, EventArgs e)
        {
            if (tooltipShown || dayViewCalendar.Selection == SelectionType.None)
                toolTipUserControlCalendar.Active = false;
            //if (dayViewCalendar.Selection == SelectionType.Appointment && dayViewCalendar.SelectedAppointment.BorderColor == Color.DeepPink)
            //  ((ToolStrip)dayViewCalendar.Parent.Parent.Parent.Controls["toolStripMedAgenda"]).Items[1].Enabled = true;
            if (this.dayViewCalendar.SelectedAppointment != null)
            {
                toolTipUserControlCalendar.SetToolTip(this.dayViewCalendar, this.dayViewCalendar.SelectedAppointment.Subject);
                toolTipUserControlCalendar.Active = true;
                tooltipShown = false;
            }
        }

        void dayViewCalendar_OnNewAppointment(object sender, NewAppointmentEventArgs e)
        {
            Appointment m_Appointment = new Appointment();
            m_Appointment.StartDate = e.StartDate;
            m_Appointment.EndDate = e.EndDate;
            m_Appointment.Subject = e.Title;
            m_Appointment.Group = "2";
            AppointmentManager.Appointments.Add(m_Appointment);
        }

        private void dayViewCalendar_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (leftClick)
            {
                if (!dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"].Visible)
                {
                    //((Panel)dayViewCalendar.Parent.Parent).Padding = new Padding(0, 50, 0, 270);
                    Appointment m_App = new Appointment();
                    m_App.StartDate = dayViewCalendar.SelectionStart;
                    m_App.EndDate = dayViewCalendar.SelectionEnd;
                    m_App.BorderColor = Color.DeepPink;
                    AppointmentRegistrationController.isNewAppointment = true;

                    ((Label)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxVisitProperties"])).Controls["labelApointmentDate"])).Text = m_App.StartDate.ToShortDateString();
                    ((Label)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxVisitProperties"])).Controls["horaEntradaLabel"])).Text = m_App.StartDate.ToShortTimeString();
                    ((Label)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxVisitProperties"])).Controls["horaSalidaLabel"])).Text = m_App.EndDate.ToShortTimeString();
                    ((Label)(((Panel)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxVisitProperties"])).Controls["panelManual"])).Controls["labelTT"])).Text = m_App.StartDate.ToString("tt");

                    AppointmentManager.Appointments.Add(m_App);
                    dayViewCalendar.Invalidate();
                    dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"].Visible = true;
                }
                AppointmentRegistrationController.logTime = 1;
            }
        }

        private void contextMenuStripCalendar_Opening(object sender, CancelEventArgs e)
        {
            if (dayViewCalendar.SelectedAppointment == null)
            {
                e.Cancel = true;
            }
            else
            {
                if (dayViewCalendar.SelectedAppointment.Subject == "Creando nueva cita...")
                {
                    e.Cancel = true;
                }
                if (!e.Cancel)
                {
                    if (dayViewCalendar.SelectedAppointment.Locked == true && dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"].Visible == false)
                    {
                        if (dayViewCalendar.SelectedAppointment.BorderColor == Color.DeepPink || dayViewCalendar.SelectedAppointment.BorderColor == Color.Green)
                        {
                            contextMenuStripCalendar.Items[0].Enabled = true;
                            contextMenuStripCalendar.Items[1].Enabled = true;
                            contextMenuStripCalendar.Items[2].Enabled = true;
                        }
                        else
                        {
                            contextMenuStripCalendar.Items[0].Enabled = true;
                            contextMenuStripCalendar.Items[1].Enabled = true;
                            contextMenuStripCalendar.Items[2].Enabled = true;
                        }
                    }
                    else
                    {
                        if (dayViewCalendar.SelectedAppointment.BorderColor == Color.DeepPink || dayViewCalendar.SelectedAppointment.BorderColor == Color.Green)
                        {
                            contextMenuStripCalendar.Items[0].Enabled = false;
                            contextMenuStripCalendar.Items[1].Enabled = false;
                            contextMenuStripCalendar.Items[2].Enabled = false;
                        }
                        else
                        {
                            contextMenuStripCalendar.Items[0].Enabled = false;
                            contextMenuStripCalendar.Items[1].Enabled = false;
                            contextMenuStripCalendar.Items[2].Enabled = false;
                        }
                    }

                    if (dayViewCalendar.SelectedAppointment.BorderColor == Color.Black)
                    {
                        contextMenuStripCalendar.Items[0].Enabled = false;
                        contextMenuStripCalendar.Items[1].Enabled = false;
                        contextMenuStripCalendar.Items[2].Enabled = false;
                    }
                }
            }
        }

        private void programarRecordatoriotoolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void editarHoraDeLaCitaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("¿Está seguro que desea editar la hora de la cita?", "Información", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if ((dayViewCalendar.SelectedAppointment != null && (dayViewCalendar.SelectedAppointment.BorderColor == Color.DeepPink || dayViewCalendar.SelectedAppointment.BorderColor == Color.Green)))
                {
                    try
                    {
                        dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"].Visible = true;
                        dayViewCalendar.SelectedAppointment.Locked = false;
                        dayViewCalendar.Invalidate();
                        AppointmentRegistrationController.isNewAppointment = false;
                        VisitModelView visit = update.GetAppointment(dayViewCalendar.SelectedAppointment.AppointmentId);


                        ((TextBox)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxPatientInformation"])).Controls["txtMrnId"])).Text = visit.IdDocumentNumber;
                        ((TextBox)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxPatientInformation"])).Controls["txtGivenName"])).Text = visit.GivenName;
                        ((TextBox)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxPatientInformation"])).Controls["txtMiddleName"])).Text = visit.MiddleName;
                        ((TextBox)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxPatientInformation"])).Controls["txtFamilyName"])).Text = visit.FamilyName;
                        ((DateTimePicker)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxPatientInformation"])).Controls["dateOfBirth_DateTimePicker"])).Value = visit.DateOfBirth;
                        ((ComboBox)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxPatientInformation"])).Controls["sex_ComboBox"])).Text = visit.Sex;
                        ((ComboBox)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxPatientInformation"])).Controls["cmbPatientType"])).SelectedItem = visit.PatientType;
                        ((CheckBox)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxPatientInformation"])).Controls["checkBoxVipPatient"])).Checked = visit.VipIndicator;
                        ((TextBox)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxPatientInformation"])).Controls["txtEmail"])).Text = visit.Email;
                        ((TextBox)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxPatientInformation"])).Controls["txtMobilePhone"])).Text = visit.MobileNumber;
                        ((TextBox)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxPatientInformation"])).Controls["txtPhoneNumber"])).Text = visit.Telephone;
                        ((TextBox)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxVisitProperties"])).Controls["textBoxPurpose"])).Text = visit.ReasonForStudy;
                        
                        ((Label)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxVisitProperties"])).Controls["labelApointmentDate"])).Text = visit.AdmitTime.ToShortDateString();
                        ((Label)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxVisitProperties"])).Controls["horaEntradaLabel"])).Text = visit.AdmitTime.ToShortTimeString();
                        ((Label)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxVisitProperties"])).Controls["horaSalidaLabel"])).Text = visit.DischargeTime.ToShortTimeString();
                        if (visit.IsAppointment)
                            ((RadioButton)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxVisitProperties"])).Controls["radAppointment"])).Checked = true;
                        else
                            ((RadioButton)(((GroupBox)(((Panel)dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"]).Controls["groupBoxVisitProperties"])).Controls["radReminder"])).Checked = true;
                        AppointmentRegistrationController.accessionNumberSelected = dayViewCalendar.SelectedAppointment.AppointmentId;
                        AgendaPatientController.currentPID = visit.MrnID;
                    }
                    catch
                    {
                        MessageBox.Show(null, "Los datos del paciente son inconcistentes. Revise la informacion completa.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        ((Panel)(dayViewCalendar.Parent.Parent.Parent.Controls["panelPatientInformation"])).Visible = false;
                        dayViewCalendar.SelectedAppointment.Locked = true;
                    }
                }
            }
        }

        private void cancelarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dayViewCalendar.SelectedAppointment != null)
            {
                string accessionNumber = dayViewCalendar.SelectedAppointment.AppointmentId;
                CancelAppointmentView cancel = new CancelAppointmentView(accessionNumber);
                cancel.ShowDialog();

                if (dayViewCalendar.SelectedAppointment.BorderColor == Color.DeepPink || dayViewCalendar.SelectedAppointment.BorderColor == Color.Green)
                {
                    if (cancel.Cancel != true)
                    {
                        dayViewCalendar.SelectedAppointment.Color = Color.Gray;
                        dayViewCalendar.SelectedAppointment.BorderColor = Color.Black;
                        dayViewCalendar.SelectedAppointment.Locked = true;
                        dayViewCalendar.SelectedAppointment.Subject = dayViewCalendar.SelectedAppointment.Subject.Replace("Pendiente", "Cancelado");
                        MessageBox.Show("La cita seleccionada ha sido cancelada.", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //((ToolStrip)dayViewCalendar.Parent.Parent.Parent.Controls["toolStripMedAgenda"]).Items[1].Enabled = false;
                        dayViewCalendar.Invalidate();
                    }
                }
                else
                {
                    MessageBox.Show("La cita seleccionada no puede ser cancelada.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }

        private void historiaMedicatoolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dayViewCalendar.SelectedAppointment != null)
            {
                string accessionNumber = dayViewCalendar.SelectedAppointment.AppointmentId;
                var oid = (from o in entities.Order_
                           from p in entities.PatientProfile_
                           where o.AccessionNumber_.Equals(accessionNumber)
                           && p.Patient__OID_.Equals(o.Patient__OID_)
                           select p).SingleOrDefault().OID_.ToString();

                PatientInformationView patientInformation = new PatientInformationView(oid, false);
                patientInformation.medicalHistory = true;
                patientInformation.Show();
            }
            
        }

        private void toolTipUserControlCalendar_Popup(object sender, PopupEventArgs e)
        {
            try
            {
                Point p = Cursor.Position;
                if (dayViewCalendar.SelectedAppointment.Subject == "Creando nueva cita..." || dayViewCalendar.Selection != SelectionType.Appointment || dayViewCalendar.Selection == SelectionType.None || !leftClick || tooltipShown)
                {
                    e.Cancel = true;
                }
                else
                {
                    tooltipShown = true;
                }
            }
            catch (Exception ex)
            { // A veces ocurre un error al hacer clicks en el control. 
            }
        }

        private void dayViewCalendar_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
                leftClick = true;
            else
                leftClick = false;
        }

        private void dayViewCalendar_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
                leftClick = true;
            else
                leftClick = false;
        }
        #endregion

        //#region Win32 API functions
        ///// uiFlags: 0 - Count of GDI objects
        ///// uiFlags: 1 - Count of USER objects
        ///// - Win32 GDI objects (pens, brushes, fonts, palettes, regions, device contexts, bitmap headers)
        ///// - Win32 USER objects:
        /////      - WIN32 resources (accelerator tables, bitmap resources, dialog box templates, font resources, menu resources, raw data resources, string table entries, message table entries, cursors/icons)
        ///// - Other USER objects (windows, menus)
        //[DllImport("user32.dll")]
        //private static extern uint GetGuiResources(IntPtr hProcess, uint uiFlags);

        //private enum ResourceType
        //{
        //    Gdi = 0,
        //    User = 1
        //}

        //[DllImport("kernel32.dll")]
        //private static extern IntPtr GetCurrentProcess();

        //[DllImport("psapi.dll")]
        //private static extern int GetProcessMemoryInfo(IntPtr hProcess, out PROCESS_MEMORY_COUNTERS counters, int size);

        //[StructLayout(LayoutKind.Sequential, Size = 40)]
        //private struct PROCESS_MEMORY_COUNTERS
        //{
        //    public int cb;
        //    public int PageFaultCount;
        //    public int PeakWorkingSetSize;
        //    public int WorkingSetSize;
        //    public int QuotaPeakPagedPoolUsage;
        //    public int QuotaPagedPoolUsage;
        //    public int QuotaPeakNonPagedPoolUsage;
        //    public int QuotaNonPagedPoolUsage;
        //    public int PagefileUsage;
        //    public int PeakPagefileUsage;
        //}
        //#endregion
    }
}
